import { camelCaseFirstChar2Upper } from '@/utils/commonUtil.js'

export function parseMysql (sql) {
  // 去除注释
  sql = sql.replace(/--.*$/gm, '')

  // 提取表名
  let tableNameMatch = sql.match(/CREATE TABLE (\w+)/i)
  let tableName = tableNameMatch ? tableNameMatch[1] : ''

  // 提取表注释
  let tableCommentMatch = sql.match(/COMMENT='(.*)'/i)
  let tableComment = tableCommentMatch ? tableCommentMatch[1] : ''

  // 提取主键
  let primaryKeyMatch = sql.match(/PRIMARY KEY \((\w+)\)/i)
  let primaryKey = primaryKeyMatch ? primaryKeyMatch[1] : ''

  const colStr = getColStr(sql)
  // 提取字段信息
  let columns = []
  const regexMatch = parseMysqlColByRegex(colStr)
  columns.push(...regexMatch)
  const className = camelCaseFirstChar2Upper(tableName)
  return {
    tableName,
    tableComment,
    primaryKey,
    columns,
    className
  }
}

export function parseOracleOrPostgresql (leftStr) {
  let split = leftStr.split(';')
  const ddlStr = split.shift()
  let result = parseMysql(ddlStr)
  const tableRegex = /COMMENT ON TABLE (\w+) IS '([^']+)';/
  const columnRegex = /COMMENT ON COLUMN (\w+)\.(\w+) IS '([^']+)';/g
  const commentStr = split.join(';')
  // 提取表名和表注释
  const tableMatch = commentStr.match(tableRegex)
  if (tableMatch) {
    result.tableComment = tableMatch[2]
  }
  // 提取列名和列注释
  let columnMatch
  while ((columnMatch = columnRegex.exec(commentStr)) !== null) {
    const columnName = columnMatch[2]
    const columnComment = columnMatch[3]
    result.columns.forEach(column => {
      if (column.name === columnName) {
        column.comment = columnComment
      }
    })
  }
  return result
}


/**
 * 对于 建表语句中的小数 decimal(5,2)这种错误分割的情况进行处理
 * @param array 要处理的数据
 * @returns {*}
 */
export function specialHandler (array) {
  for (let i = array.length - 1; i >= 0; i--) {
    let currentItem = array[i]
    if (/^\d/.test(currentItem)) {  // 使用正则表达式判断是否以数字开头
      let prevItem = array[i - 1]
      array[i - 1] = prevItem + ',' + currentItem
      array.splice(i, 1)
    }
  }
  return array
}

export function parseMysqlColByRegex (colStr) {
  let split = colStr.split(',')
  split = specialHandler(split)
  let columns = []

  split.forEach(item => {
    item = item.toLowerCase()
    if (!item.includes('primary key')) {
      const colSplit = item.replaceAll('\n', '')
        .trim()
        .split(' ')
      let comment = ''
      if (colSplit[colSplit.length - 2] === 'comment') {
        comment = colSplit[colSplit.length - 1]
      }
      columns.push({
        name: colSplit[0],
        type: colSplit[1],
        comment
      })
    }
  })
  return columns
}

export function getColStr (sql) {
  const from = sql.indexOf('(') + 1
  const to = sql.lastIndexOf(')')
  return sql.substring(from, to)
}

export function beautifySQL (sql) {
  // 增加换行和缩进
  sql = sql.replace(/SELECT /ig, '\n  SELECT \n\t ')
    .replace(/INSERT /ig, '\n  INSERT ')
    .replace(/UPDATE /ig, '\n  UPDATE \n\t')
    .replace(/DELETE /ig, '\n  DELETE \n\t')
    .replace(/FROM /ig, '\n  FROM ')
    .replace(/INTO /ig, ' INTO ')
    .replace(/SET /ig, '\n  SET \n\t ')
    .replace(/WHERE /ig, '\n  WHERE ')
    .replace(/AND /ig, '\n\t  AND ')
    .replace(/OR /ig, '\n\t  OR ')
    .replace(/VALUES /ig, '\n  VALUES ')
    .replace(/OR /ig, '\n\t  OR ')
    .replace(/,/ig, ',\n\t')

  // 处理条件中的括号和空格
  sql = sql.replace(/WHERE \(/ig, '\n  WHERE (')
    .replace(/AND \(/ig, '\n\t  AND (')
    .replace(/OR \(/ig, '\n\t  OR (')
    .replace(/\( /ig, '(').replace(/ \)/g, ')')

  // 使每个 JOIN 的表单独起一行
  sql = sql.replace(/LEFT JOIN /ig, '\n  LEFT JOIN ')
    .replace(/RIGHT JOIN /ig, '\n  RIGHT JOIN ')
    .replace(/INNER JOIN /ig, '\n  INNER JOIN ')

  return sql
}
